package com.tt.aidltryerclient;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.tt.aidltryer.serviceinterface.IReplyer;
import com.tt.aidltryer.serviceinterface.IReplyer.Stub;

public class MainActivity extends Activity {

    IReplyer mIReplyer;

    private TextView mAnswer;

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("kyson", "客户端已经连上服务器");
            mIReplyer = Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("kyson", "客户端断开与服务器连接");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAnswer = (TextView) this.findViewById(R.id.textView4);

        Intent intent = new Intent("android.intent.action.ReplyerService");
        bindService(intent, conn, Context.BIND_AUTO_CREATE);

        findViewById(R.id.textView).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    String ques = "hey!";
                    Log.i("kyson", "发送：" + ques);
                    mIReplyer.qustion(ques);

                    String ans = mIReplyer.answer();
                    Log.i("kyson", "回答：" + ans);
                    mAnswer.setText(ans);

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        findViewById(R.id.textView2).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    String ques = "h r u?";
                    Log.i("kyson", "发送：" + ques);
                    mIReplyer.qustion(ques);
                    String ans = mIReplyer.answer();
                    Log.i("kyson", "回答：" + ans);
                    mAnswer.setText(ans);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
